<template>
  <div>
    <!--
    给editor加key是因为给tinymce keep-alive以后组件切换时tinymce编辑器会显示异常，
    在activated钩子里改变key的值可以让编辑器重新创建
  -->
    <editor :id="id" ref="myEditor" :key="tinymceFlag" v-model="content" :init="tinymceInit" />

    <!-- 上传文件 -->
    <input
      :id="tinymceFlag + 1"
      ref="inputer"
      type="file"
      name="file"
      style="display:none"
      @change="handleFileChange"
      @touchstart="handleFileChange"
    >
    <!-- 上传视频 -->
    <el-dialog title="上传视频" :visible.sync="uploadVideo">
      <div style="line-height: 1; margin-bottom: 20px;">
        <el-alert
          title="请先上传视频封面图片"
          type="info"
          description="封面图片仅支持jpg/png格式，视频暂时仅支持mp4格式"
          show-icon
          :closable="false"
        />
      </div>
      <upload :data="imgData" :model="model" />
      <div slot="footer" class="dialog-footer">
        <el-button :loading="uploading" @click="uploadVideo = false">取 消</el-button>
        <el-button
          :loading="uploading"
          type="primary"
          :disabled="!imgData.imgUrl"
          @click="uploadfile"
        >上传视频</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { uploadFile } from 'api/common'
import Upload from 'components/Upload/img-upload'

import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/silver/theme'
import Editor from '@tinymce/tinymce-vue'

import 'tinymce/plugins/textcolor'
import 'tinymce/plugins/advlist'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/paste'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/searchreplace'
import 'tinymce/plugins/hr'
import 'tinymce/plugins/link'
import 'tinymce/plugins/insertdatetime'
import 'tinymce/plugins/emoticons'

export default {
  name: 'TinymceEditor',
  components: {
    'editor': Editor,
    Upload
  },
  props: {
    // 是否需要显示视频上传按钮
    showVideoBtn: {
      type: Boolean,
      required: false
    },
    // 是否展示超链接
    showHyperlinkBtn: {
      type: Boolean,
      required: false
    },
    uploadModel: {
      type: String,
      default: 'kdeHelp'
    },
    model: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      tinymceFlag: this.$route.query.id || 1,
      tinymceInit: {},
      content: '',
      editor: {},
      form: {
        imageFile: null,
        module: '/kdeEditor',
        model: 'kdeHelp'
      },
      uploading: false,
      id: `tinymceEditor${Math.floor(Math.random() * 10000)}`,
      uploadVideo: false,
      imgData: {
        myId: Math.random(),
        model: 'kdeHelp',
        imgUrl: '',
        ImgSize: 300,
        text: '视频封面图片大小不得超过300k'
      },
      videoId: `tinymceEditor${Math.floor(Math.random() * 10000)}`
    }
  },
  created() {
    // const that = this
    this.tinymceInit = {
      skin_url: 'static/tinymce/skins/ui/oxide',
      language_url: 'static/tinymce/langs/zh_CN.js',
      language: 'zh_CN',
      height: document.body.offsetHeight - 300,
      browser_spellcheck: true, // 拼写检查
      branding: false, // 隐藏右下角技术支持
      elementpath: false, // 禁用编辑器底部的状态栏
      statusbar: false, // 隐藏编辑器底部的状态栏
      paste_data_images: true, // 允许粘贴图像
      convert_urls: false,
      // menubar: true, // 隐藏最上方menu
      fontsize_formats: '12px 14px 16px 18px 24px 36px 48px',
      plugins: 'advlist table lists paste preview fullscreen searchreplace hr insertdatetime link emoticons',
      toolbar: [
        'newdocument searchreplace undo redo | styleselect fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent ',
        `hr bold italic underline strikethrough removeformat |
        insertdatetime table |
        link imageUpload ${this.showVideoBtn ? 'videoUpload' : ''} |
        preview fullscreen code emoticons`
      ],
      link_assume_external_targets: true,
      /**
       * 下面方法是为tinymce添加自定义插入图片按钮
       * 借助iview的Upload组件,将图片先上传到存储云上，再将图片的存储地址放入编辑器内容
       */
      setup: (editor) => {
        // console.log('editor', editor)
        this.editor = editor
        editor.ui.registry.addButton('imageUpload', {
          tooltip: '插入图片',
          icon: 'image',
          onAction: () => {
            this.uploadfile()
          }
        })
        editor.ui.registry.addButton('videoUpload', {
          text: '视频',
          tooltip: '插入视频',
          onAction: () => {
            if (!this.showVideoBtn) {
              this.$alert('当前模块不支持上传视频', '提示', {
                confirmButtonText: '确认',
                type: 'warning'
              })
              return
            }
            this.uploadVideo = true
          }
        })
      }
    }
    if (this.uploadModel) {
      this.form.model = this.uploadModel
      this.imgData.model = this.uploadModel
    }
  },
  activated() {
    this.tinymceFlag++
  },
  mounted() {

  },
  methods: {
    // 将编辑器内的内容传到父组件
    onEditorChange() {
      // 将图片内网域名转换为外网域名
      const data = this.editor.getContent()
      return data
    },

    // 设置编辑器内容
    edit(data) {
      this.editor.setContent(data)
    },

    // 获取上传图片宽高
    checkImg(file, isImage) {
      return new Promise((resolve, reject) => {
        if (isImage && !this.uploadVideo) {
          // console.log('file.size', file.size)
          const isLt2M = file.size / 1024 < 1024 + 1
          if (!isLt2M) {
            this.$alert(`上传图片大小不能超过1M！`, '提示', {
              confirmButtonText: '确认',
              type: 'warning'
            })
            return
          }
          // 图片格式
          const isJPG = file.type === 'image/jpeg'
          const isPNG = file.type === 'image/png'
          const isGIF = file.type === 'image/gif'
          const isBMP = file.type === 'image/bmp'
          if (!isJPG && !isPNG && !isGIF && !isBMP) {
            this.$alert('图片的格式暂时仅支持png或者jpg或者bmp或者gif格式哦～', '提示', {
              confirmButtonText: '确认',
              type: 'warning'
            })
            return
          }
          const reader = new window.FileReader()
          reader.onload = () => {
            const image = new window.Image()
            image.src = reader.result
            image.onload = () => {
              const sizeInfo = {}
              sizeInfo.width = image.width
              sizeInfo.height = image.height
              resolve(sizeInfo)
            }
          }
          reader.readAsDataURL(file)
        } else if (file.type.includes('video')) {
          const isMP4 = file.type === 'video/mp4'
          if (!isMP4) {
            this.$alert('图片的格式暂时仅支持mp4格式哦～', '提示', {
              confirmButtonText: '确认',
              type: 'warning'
            })
            return
          }
          resolve({
            width: '',
            height: ''
          })
        } else {
          this.$alert('请上传正确格式的文件', '提示', {
            confirmButtonText: '确认',
            type: 'warning'
          })
          reject()
        }
      })
    },

    // 上传文件 图片/视频
    handleFileChange() {
      if (this.uploading) {
        return
      }
      const inputDOM = this.$refs.inputer
      const file = inputDOM.files[0]
      // 判断是否是图片上传
      const imageType = /image.*/
      const isImage = file.type.match(imageType)
      this.checkImg(file, isImage).then((imgInfo) => {
        this.uploading = true
        const formData = new window.FormData()
        Object.keys(this.form).forEach((y) => {
          formData.append(y, this.form[y])
        })
        formData.append('file', file)
        uploadFile(formData, this.model).then((re) => {
          this.uploading = false
          const { code, data } = re
          if (code === '000000') {
            this.setFileHtml(isImage, data, imgInfo)
          } else {
            this.$alert(re.msg, '提示', {
              confirmButtonText: '确认',
              type: 'warning'
            })
          }
        })
        this.$refs.inputer.value = ''
      }).catch((err) => {
        this.uploading = false
        console.log('上传图片视频--err', err)
      })
    },

    setFileHtml(isImage, data, imgInfo) {
      if (isImage) {
        const mainPath = `/${data.relativePath}&w=${imgInfo.width}&h=${imgInfo.height}`
        const inHtml = `
              <img
                class="wscnph"
                style="max-width: 100%;height: auto;"
                src="${mainPath}" width="${imgInfo.width}"
                height="${imgInfo.height}">`
        console.log(inHtml)
        // this.editor.insertContent(inHtml)
        tinymce.execCommand('mceInsertContent', false, inHtml)
      } else {
        if (!this.uploadVideo) {
          this.imgData.imgUrl = ''
          return
        }
        const fileUrl = `/${data.relativePath}`
        const inHtml = `
                <div>
                  <p style="padding-bottom: 10px;" />
                  <p>
                    <video
                      controls
                      x5-playsinline playsinline webkit-playsinline
                      poster="/${this.imgData.imgUrl}"
                      style="width: 100%;height: auto;
                      object-fit: fill" >
                        <source src="${fileUrl}" type="video/mp4" />
  		                  您的浏览器不支持video标签播放视频
                    </video>
                  </p>
                </div>
                <p style="padding-bottom: 10px;" />`
        // this.editor.insertContent(inHtml)
        tinymce.execCommand('mceInsertContent', false, inHtml)
        this.uploadVideo = false
        this.imgData.imgUrl = ''
      }
    },

    uploadfile() {
      window.document.getElementById(this.tinymceFlag + 1).click()
    }
  }
}
</script>

